import numpy as np
import pandas as pd
from factor_analyzer import FactorAnalyzer
from sklearn.decomposition import PCA, FactorAnalysis
from sklearn import preprocessing
import math

df = pd.read_csv("F:/成信大/多元统计分析/test4-2.csv")
columns = df.shape[1]
data = df.columns[2: columns]
df = np.array(df[data])
# 数据标准化
df = preprocessing.scale(df)
# 协方差矩阵的特征值和特征向量
pca = PCA(n_components=8)
# 主成分得分
pca.fit(df)
# 载荷（因子负荷量）
print("载荷（因子负荷量）：\n", pca.components_[0])
pca.fit(df)  # 训练PCA模型
print("pca模型得到的特征值（从大到小）:", pca.explained_variance_, sep='\n')
# 因子载荷
# eigValues, eigVectors = np.linalg.eig(pca.components_)
# print(eigVectors)
# print(eigVectors * (eigValues ** 0.5))
pvr = pca.explained_variance_ratio_  # 返回各个成分各自的方差百分比
print("各个成分的方差百分比：", pvr, sep='\n')
ca = np.cumsum(pvr)  # 计算累计贡献率
print("累计贡献率：", ca, sep='\n')
coefficient = []
j = 0
for i in pca.components_[0]:
    coefficient.append(round(pca.components_[0][j], 4))
    j = j + 1
# print("方差贡献即特征值的算术平方根：\n", sqrt)
# print("主成分系数：\n", coefficient)
x = []
for i in range(len(coefficient)):
    x.append(round(coefficient[i], 8))
print(
    "主成分表达式：Z = {}*X1+{}*X2+{}*X3+{}*X4+{}*X5+{}*X6+{}*X7+{}*X8".format(x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7]))
